﻿using vite_entity.Entities;
using vite_net.Controllers.User.UserInfo;

namespace vite_net.Common
{
    public class MenuHandler
    {
        /// <summary>
        /// 生成菜单，递推，只有2级的
        /// </summary>
        /// <param name="sysMenus"></param>
        /// <returns></returns>
        public static List<Response_Menus> GenerateMenus(List<SysMenu> sysMenus)
        {
            List<Response_Menus> rtMenus = new List<Response_Menus>();
            foreach (var menu in sysMenus.Where(x => x.ParentId == 0).OrderBy(x => x.Sort))
            {
                var rtMenu = GenerateResponseMenuByDbMenu(menu);
                rtMenu.Children = GenerateChild(menu, sysMenus);
                rtMenus.Add(rtMenu);
            }
            return rtMenus;
        }

        private static Response_Menus GenerateResponseMenuByDbMenu(SysMenu menu)
        {
            return new Response_Menus()
            {
                Id = menu.Id,
                Path = menu.RoutePath ?? string.Empty,
                Name = menu.Name,
                Component = menu.Component ?? string.Empty,
                Title = menu.Name,
                Buttons =  menu.Perm?.Split("-"),
                Icon = menu.Icon ?? string.Empty
            };
        }

        private static List<Response_Menus> GenerateChild(SysMenu menu, List<SysMenu> sysMenus)
        {
            List<Response_Menus> rtChildMenus = new List<Response_Menus>();
            foreach (var childMenu in sysMenus.Where(x => x.ParentId == menu.Id).OrderBy(x => x.Sort))
            {
                var tempMenu = GenerateResponseMenuByDbMenu(childMenu);
                rtChildMenus.Add(tempMenu);
                tempMenu.Children = GenerateChild(childMenu, sysMenus);
            }
            return rtChildMenus;
        }
    }
}
